package com.zmn.oms.admin.controller.common;

import com.google.api.client.util.Lists;
import com.zmn.base.channel.common.constant.RelationTypeConsts;
import com.zmn.base.channel.common.dro.CooperateRelationDRO;
import com.zmn.base.common.data.common.dro.marketing.shop.MarketingShopDRO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.admin.controller.order.OrderBaseController;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.query.shop.MarketingShopQuery;
import com.zmn.oms.model.vo.shop.ExternalShopVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author sunlife
 * @date 2019/11/13 19:51
 */
@Controller
@RequestMapping("/shop")
public class ShopController extends OrderBaseController {

    @RequestMapping("list/query")
    @ResponseBody
    public ResultDTO query(@RequestParam(value = "plat", required = false) Integer plat,
                           @RequestParam(value = "shopType", required = false) Integer shopType,
                           @RequestParam(value = "sourceCompanyId", required = false) Integer sourceCompanyId,
                           @RequestParam(value = "name", required = false) String name) {
        return ResultDTO.success(super.getShopList(plat, shopType, sourceCompanyId, name));
    }

    @GetMapping("/list/external")
    @ResponseBody
    public ResultDTO listExternalShop(@RequestParam(value = "cityId") Integer cityId,
                           @RequestParam(value = "channelId") Integer channelId) {
        // TODO wyc 删除日志
        logger.info("relationRemoteService.listRelationByIdAndType channelId={}", channelId);
        ResponseDTO<List<CooperateRelationDRO>> listResponseDTO = relationRemoteService.listRelationByIdAndType(channelId, RelationTypeConsts.RELATION_TYPE_CHANNEL);
        logger.info("relationRemoteService.listRelationByIdAndType listResponseDTO={}", listResponseDTO);
        if (!listResponseDTO.isSuccess()) {
            return ResultDTO.fail(String.format("三级渠道查询失败：%s", listResponseDTO.getMessage()));
        }
        if (CollectionUtil.isNullOrEmpty(listResponseDTO.getData())) {
            return ResultDTO.fail("三级渠道查询结果为空！");
        }
        Integer channelThreeId = listResponseDTO.getData().get(0).getObjectId();
        logger.info("marketingShopListRemoteService.listShopByChannelThreeIdAndCity channelThreeId={},cityId={}", channelThreeId, cityId);
        ResponseDTO<List<MarketingShopDRO>> shopListResponseDTO = marketingShopListRemoteService.listShopByChannelThreeIdAndCity(channelThreeId, cityId);
        logger.info("marketingShopListRemoteService.listShopByChannelThreeIdAndCity shopListResponseDTO={}", shopListResponseDTO);
        if (!shopListResponseDTO.isSuccess()) {
            return ResultDTO.fail(String.format("关联店铺查询失败：%s", shopListResponseDTO.getMessage()));
        }
        if (CollectionUtil.isNullOrEmpty(shopListResponseDTO.getData())) {
            return ResultDTO.fail("关联店铺查询结果为空！");
        }
        List<ExternalShopVO> voList = Lists.newArrayListWithCapacity(shopListResponseDTO.getData().size());
        for (MarketingShopDRO dro : shopListResponseDTO.getData()) {
            ExternalShopVO vo = new ExternalShopVO();
            vo.setExternalShopId(dro.getThrShopId());
            vo.setInternalShopId(dro.getShopId());
            vo.setInternalShopName(dro.getName());
            vo.setInternalBranchShopName(dro.getBranchName());
            if (StringUtil.isBlank(dro.getBranchName())) {
                vo.setShowShopName(dro.getName());
            }else {
                vo.setShowShopName(String.format("%s（%s）", dro.getName(), dro.getBranchName()));
            }
            voList.add(vo);
        }
        return ResultDTO.success(voList);
    }

    @RequestMapping("list/marketing")
    @ResponseBody
    public ResultDTO queryMarketingShop(MarketingShopQuery body) {
        if (StringUtil.isBlank(body.getKeyword())) {
            return ResultDTO.success(Lists.newArrayList());
        }
        String keyWord = body.getKeyword().replaceAll("\\(|\\)|（|）", "").trim();
        com.zmn.base.common.data.common.query.marketing.shop.MarketingShopQuery marketingShopQuery = new com.zmn.base.common.data.common.query.marketing.shop.MarketingShopQuery();
        if (NumberUtil.isNumber(keyWord)) {
            marketingShopQuery.setShopId(Integer.parseInt(keyWord));
        }else {
            marketingShopQuery.setFullName(keyWord);
            marketingShopQuery.setStatus(body.getStatus());
        }
        marketingShopQuery.setPageIndex(body.getPageIndex());
        marketingShopQuery.setPageSize(body.getPageSize());
        ResponseDTO<List<MarketingShopDRO>> listResponseDTO = null;
        try {
            listResponseDTO = marketingShopListRemoteService.listByQuery(marketingShopQuery);
        } catch (Exception e) {
            logger.error("marketingShopListRemoteService.listByQuery error={}", e);
            return ResultDTO.success(Lists.newArrayList());
        }
        logger.debug("marketingShopListRemoteService.listByQuery query={},listResponseDTO={}", marketingShopQuery, listResponseDTO);
        if (!listResponseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(listResponseDTO.getData())) {
            return ResultDTO.success(Lists.newArrayList());
        }
        List<ExternalShopVO> voList = Lists.newArrayListWithCapacity(listResponseDTO.getData().size());
        for (MarketingShopDRO dro : listResponseDTO.getData()) {
            ExternalShopVO vo = new ExternalShopVO();
            vo.setCooperationId(dro.getCooperationId());
            vo.setExternalShopId(dro.getThrShopId());
            vo.setInternalShopId(dro.getShopId());
            vo.setInternalShopName(dro.getName());
            vo.setInternalBranchShopName(dro.getBranchName());
            if (StringUtil.isBlank(dro.getBranchName())) {
                vo.setShowShopName(String.format("%s-%s", dro.getName(), dro.getChannelThrName()));
            }else {
                vo.setShowShopName(String.format("%s（%s）-%s", dro.getName(), dro.getBranchName(), dro.getChannelThrName()));
            }
            voList.add(vo);
        }
        return ResultDTO.success(voList);
    }
}
